const WLog4 = require('@/lib/log4/index');
const LogsMongo = require('@mongodb/logs')

/**
 * 错误处理
 * @param ctx 环境上下文
 * @param next 下一步
 * @returns {Promise<void>}
 */
const logger = async (ctx, next) => {
	// 错误处理
	try {
		await next();
	} catch(err) {
		console.log('error = ', err)
		const status = err.code ? 200 : err.statusCode || err.status || 500

		// ===================== log4 ==================
		const errCode = err.code ? `${err.code}` : ''
		const errorMsg = `${status} ${ errCode } ${err.message || err.msg}`
		WLog4.error(errorMsg)

		// ===================== 数据库日志 ==================
		const obj = {
			statusCode: String(status),
			errCode: errCode,
			msg: err.message || err.msg
		}
		LogsMongo.addServerError(obj)

		ctx.status = status
		ctx.response.body = {
			code: err.code,
			msg: err.msg,
		}
	}
}

module.exports = logger
